package com.glq1218.comment.controller;

import com.glq1218.comment.bo.AddCommentBO;
import com.glq1218.comment.bo.CommentBO;
import com.glq1218.comment.bo.QueryCommentBO;
import com.glq1218.comment.dto.AddCommentDTO;
import com.glq1218.comment.dto.CommentDTO;
import com.glq1218.comment.dto.QueryCommentDTO;
import com.glq1218.comment.entity.Comment;
import com.glq1218.comment.service.CommentService;
import com.glq1218.domain.*;
import com.glq1218.util.BeanCopyUtils;
import com.glq1218.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author glq1218
 * @description 评论控制器
 * @since 2023/4/21 14:58
 */
@RestController
@RequestMapping("/api/comment")
@RequiredArgsConstructor
public class CommentController {
    private final CommentService commentService;

    @GetMapping
    public R<PaginationResult<CommentDTO>> queryCommentList(PaginationParam paginationParam, SortParam sortParam, IntervalStr intervalStr, QueryCommentDTO queryCommentDTO) {
        QueryCommentBO queryCommentBO = BeanCopyUtils.copyBean(queryCommentDTO, QueryCommentBO.class);
        PaginationResult<CommentBO> paginationResult = commentService.queryCommentList(paginationParam, sortParam, intervalStr, queryCommentBO);
        // 获取BO转换为DTO
        List<CommentDTO> commentDTOList = new ArrayList<>();
        // 结果不为空才能进行转换
        if (Objects.nonNull(paginationResult.getRecords())) {
            List<CommentBO> records = paginationResult.getRecords();
            commentDTOList = BeanCopyUtils.copyBeanList(records, CommentDTO.class);
        }
        return R.ok(PaginationResult
                .<CommentDTO>builder()
                .total(paginationResult.getTotal())
                .records(commentDTOList)
                .build()
        );
    }

    @PostMapping
    public R<?> addComment(@RequestBody AddCommentDTO addCommentDTO) {
        AddCommentBO addCommentBO = BeanCopyUtils.copyBean(addCommentDTO, AddCommentBO.class);
        Long userId = SecurityUtils.getUserId();
        addCommentBO.setUserId(userId);
        Comment comment = BeanCopyUtils.copyBean(addCommentBO, Comment.class);
        boolean saved = commentService.save(comment);
        if (saved) {
            return R.ok("添加评论成功");
        }
        throw new RuntimeException("添加评论失败");
    }

    @DeleteMapping
    public R<?> deleteComment(@RequestParam("idList") List<Long> idList) {
        return R.ok(commentService.removeByIds(idList));
    }
}
